/**
 * author: sam long
 * date: 2017-11-29
 * question:
 *      1. 是否可以增加一个root属性，表示根状态器
 */

import IStore from '../interface/istore';
import StoreOpt from '../model/storeOpts';
import Dictionary from '../model/dictionary';

/**
 * 存储状态类
 */
class Store implements IStore  {
    opt: StoreOpt;
    state: any;
    protected entities: Dictionary<any> = new Dictionary<any>();
    protected getters: Dictionary<any> = new Dictionary<any>();
    constructor(opt: StoreOpt) {
        this.opt = opt;
        this.state = opt.state;
        this.mapActions();
        this.mapGet();
    }
    dispatch(key:string, payload:any){
        return this.entities[key](payload);
    }
    get(key:string){
        return this.getters[key]();
    }

    private mapActions(){
        let actions = this.opt.actions;
        let that = this;
        for(let key in actions){// action必须是 function类型
            that.entities[key] = function wrapHandler(payload){
                return actions[key].call(that, that.state, payload);
            }
        }
    }
    private mapGet(){
        let getters = this.opt.getters;
        let that = this;
        for(let key in getters){
            that.getters[key] = function wrapHandler(){
                return getters[key].call(that, that.state);
            }
        }
    }

}

export default Store;
